package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.utils.SecurityUtils;
import com.rla.common.utils.StringUtils;
import com.rla.mapper.EhsEverydayBloodGlucoseMapper;
import com.rla.mapper.VipUserInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.rla.domain.bo.BaseHealthTargetRuleBo;
import com.rla.domain.vo.BaseHealthTargetRuleVo;
import com.rla.domain.BaseHealthTargetRule;
import com.rla.mapper.BaseHealthTargetRuleMapper;
import com.rla.service.IBaseHealthTargetRuleService;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 健康数据指标规则Service业务层处理
 *
 * @author rla
 * @date 2025-07-30
 */
@RequiredArgsConstructor
@Service
public class BaseHealthTargetRuleServiceImpl implements IBaseHealthTargetRuleService {

    private final BaseHealthTargetRuleMapper baseMapper;
    private final EhsEverydayBloodGlucoseMapper bloodGlucoseMapper;

    /**
     * 查询健康数据指标规则
     */
    @Override
    public BaseHealthTargetRuleVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询健康数据指标规则列表
     */
    @Override
    public TableDataInfo<BaseHealthTargetRuleVo> queryPageList(BaseHealthTargetRuleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseHealthTargetRule> lqw = buildQueryWrapper(bo);
        Page<BaseHealthTargetRuleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询健康数据指标规则列表
     */
    @Override
    public List<BaseHealthTargetRuleVo> queryList(BaseHealthTargetRuleBo bo) {
        LambdaQueryWrapper<BaseHealthTargetRule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseHealthTargetRule> buildQueryWrapper(BaseHealthTargetRuleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseHealthTargetRule> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTargetId()), BaseHealthTargetRule::getTargetId, bo.getTargetId());
        lqw.eq(StringUtils.isNotBlank(bo.getMeasureType()), BaseHealthTargetRule::getMeasureType, bo.getMeasureType());
        lqw.like(StringUtils.isNotBlank(bo.getMeasureName()), BaseHealthTargetRule::getMeasureName, bo.getMeasureName());
        lqw.like(StringUtils.isNotBlank(bo.getPhaseName()), BaseHealthTargetRule::getPhaseName, bo.getPhaseName());
        lqw.eq(bo.getMinValue() != null, BaseHealthTargetRule::getMinValue, bo.getMinValue());
        lqw.eq(bo.getMaxValue() != null, BaseHealthTargetRule::getMaxValue, bo.getMaxValue());
        lqw.eq(bo.getSort() != null, BaseHealthTargetRule::getSort, bo.getSort());
        return lqw;
    }

    /**
     * 新增健康数据指标规则
     */
    @Override
    public Boolean insertByBo(BaseHealthTargetRuleBo bo) {
        BaseHealthTargetRule add = BeanUtil.toBean(bo, BaseHealthTargetRule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改健康数据指标规则
     */
    @Override
    public Boolean updateByBo(BaseHealthTargetRuleBo bo) {
        BaseHealthTargetRule update = BeanUtil.toBean(bo, BaseHealthTargetRule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseHealthTargetRule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除健康数据指标规则
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> calculateIndicators(String targetName,String measureType,Double measureValue) {
        Map<String,Object> map = new HashMap<>();

        List<BaseHealthTargetRuleVo> list = baseMapper.queryRlueByMeasureType(targetName, measureType);
        for (BaseHealthTargetRuleVo vo : list) {
            Double minValue = vo.getMinValue();
            Double maxValue = vo.getMaxValue();
            if(ObjectUtil.isNotEmpty(minValue) && ObjectUtil.isNotEmpty(maxValue)){
                if(minValue<=measureValue && maxValue>=measureValue){
                    map.put("tag", vo.getPhaseName());
                    map.put("color", vo.getColor());
                    break;
                }
            }else if(ObjectUtil.isNotEmpty(minValue) && ObjectUtil.isEmpty(maxValue)){
                if(minValue<=measureValue){
                    map.put("tag", vo.getPhaseName());
                    map.put("color", vo.getColor());
                    break;
                }
            }


        }
        return map;
    }


}
